package com.idconfirmsystem.activity;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.KJFragment;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dtr.zxing.activity.CaptureActivity;
import com.google.gson.JsonObject;
import com.idconfirmsystem.Conf;
import com.idconfirmsystem.R;
import com.idconfirmsystem.app.AppConfig;
import com.idconfirmsystem.app.AppContext;
import com.idconfirmsystem.dialog.SweetAlertDialog;
import com.idconfirmsystem.fragment.AMTaskFragment;
import com.idconfirmsystem.fragment.BagVerifyFragment;
import com.idconfirmsystem.fragment.BagVerifyListFragment;
import com.idconfirmsystem.fragment.BagVerifyQueryListFragment;
import com.idconfirmsystem.fragment.MidTaskFragment;
import com.idconfirmsystem.fragment.PMTaskFragment;
import com.idconfirmsystem.fragment.RecevieMsgFragment;
import com.idconfirmsystem.fragment.SendMsgFragment;
import com.idconfirmsystem.fragment.TaskFragment;
import com.idconfirmsystem.handler.MainHandler;
import com.idconfirmsystem.lib.ActionBarDrawerToggle;
import com.idconfirmsystem.lib.DrawerArrowDrawable;
import com.idconfirmsystem.lib.RoundedImageView;
import com.idconfirmsystem.lib.toast.Crouton;
import com.idconfirmsystem.lib.toast.Style;
import com.idconfirmsystem.model.UserBean;
import com.idconfirmsystem.model.UserMenu;
import com.idconfirmsystem.service.AppUpdateService;
import com.idconfirmsystem.util.ACache;
import com.idconfirmsystem.util.CommonHelper;
import com.idconfirmsystem.util.DoubleClickExitHelper;
import com.idconfirmsystem.util.CommonHelper.MenuName;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.f;

public class MainActivity extends KJActivity {

	// 运行时临时变量
	private RuntimeObject ru = new RuntimeObject();

	public class RuntimeObject {
		private DoubleClickExitHelper doubleClickExitHelper;
		private TranslateAnimation myAnimation_Left;
		private long exitTime = 0;
		private Boolean openOrClose = false;
		private int versionCode;// 获取当前版本号
		private ACache mCache;
		private boolean isLogin = false;
		// 定时清理缓存
		private Timer mTimer;
		private TimerTask mTimerTask;

		private File sdcardDir;
		private String path;
		private File f;
		private File[] fl;
		private String[] menus = null;
		private String[] enmenus = null;
	}

	// 配套Handler
	private Handler handler = new MainHandler(MainActivity.this);

	// 布局元素
	private Element el = new Element();

	public class Element {
		private DrawerLayout mDrawerLayout;
		private ListView mDrawerList;
		private RelativeLayout rl;
		private ActionBarDrawerToggle mDrawerToggle;
		private DrawerArrowDrawable drawerArrow;
		private RoundedImageView headRoundedImage;
		private TextView userName;
		private RelativeLayout toprl;
		private ImageView loginTextView;
		private LinearLayout animLinearLayoutId;
	}

	public static FragmentManager fm;
	protected static final int UPDATE_TEXT = 0;

	private TaskFragment taskFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initMainView();

		createSDCardDir();

		ru.versionCode = getVersionCode(this);
		// chekedVersionCode();//版本更新检测
		MobclickAgent.updateOnlineConfig(this);

		ActionBar ab = getActionBar();
		ab.setDisplayHomeAsUpEnabled(true);
		ab.setHomeButtonEnabled(true);

		init();// 初始化fragment
		fm = this.getSupportFragmentManager();

		// clearCache();
	}

	/**
	 * 初始化主界面
	 * 
	 * @author 吴晓明
	 * @throw
	 * @return void
	 */
	private void initMainView() {
		ru.mCache = ACache.get(this);
		ru.doubleClickExitHelper = new DoubleClickExitHelper(this);
		el.toprl = (RelativeLayout) findViewById(R.id.toprl);
		el.animLinearLayoutId = (LinearLayout) findViewById(R.id.animll_id);
		el.loginTextView = (ImageView) findViewById(R.id.login_tv);
		el.userName = (TextView) findViewById(R.id.user_name);
		el.headRoundedImage = (RoundedImageView) findViewById(R.id.iv_main_left_head);

		el.rl = (RelativeLayout) findViewById(R.id.rl);
		el.mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		el.mDrawerList = (ListView) findViewById(R.id.navdrawer);

		setTitle("武装押运智能化管控平台");

		int i = Conf.LoginConf.ACCOUNT_TYPE;
		if (i == 1) {
			// ru.menus = new String[] { "早送任务", "中调任务", "晚接任务", "消息发送", "消息通知",
			// "密码修改" };
			ru.menus = CommonHelper.UserLists.convertRightsList(UserBean.getInstance().getUserLists());
		} else if (i == 2) {
			// ru.menus = new String[] { "早送任务", "中调任务", "晚接任务", "收款任务", "送款任务",
			// "箱包交接核对", "箱包交接查询", "消息发送", "消息通知", "密码修改" };
			ru.menus = CommonHelper.UserLists.convertRightsList(UserBean.getInstance().getUserLists());
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item_text, ru.menus);
		el.mDrawerList.setAdapter(adapter);
		el.mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@SuppressLint({ "ResourceAsColor", "Recycle" })
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				switchTask(position);
				// TextView taskTitle = (TextView)
				// findViewById(R.id.tv_taskcode);
				// taskTitle.setText(ru.menus[position]);

				el.mDrawerLayout.closeDrawers();
				ru.openOrClose = false;
			}
		});

		el.drawerArrow = new DrawerArrowDrawable(this) {
			@Override
			public boolean isLayoutRtl() {
				return false;
			}
		};
		el.mDrawerToggle = new ActionBarDrawerToggle(this, el.mDrawerLayout, el.drawerArrow, R.string.drawer_open,
				R.string.drawer_close) {

			public void onDrawerClosed(View view) {
				super.onDrawerClosed(view);
				invalidateOptionsMenu();
				ru.openOrClose = false;
			}

			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				invalidateOptionsMenu();
				ru.openOrClose = true;
			}
		};
		el.mDrawerLayout.setDrawerListener(el.mDrawerToggle);
		el.mDrawerToggle.syncState();

		el.toprl.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (ru.isLogin == true) {
					Intent it = new Intent(getApplicationContext(), SettingActivity.class);
					startActivityForResult(it, 1);
					// overridePendingTransition(R.anim.push_left_in,
					// R.anim.push_left_out);
					overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
				} else {
					// sinaLogin();//暂时关闭关联端口
				}

			}
		});

	}

	@TargetApi(19)
	private void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	private void clearCache() {
		ru.sdcardDir = Environment.getExternalStorageDirectory();
		ru.path = ru.sdcardDir.getPath() + "/IdConfirmData";
		ru.f = new File(ru.path);
		ru.fl = ru.f.listFiles();
		Log.e("fl.length==", ru.fl.length + "");
		if (ru.fl.length == 0) {

		} else {

			for (int i = 0; i < ru.fl.length; i++) {
				if (ru.fl[i].toString().endsWith(".mp3") || ru.fl[i].toString().endsWith(".MP3")) {
					ru.fl[i].delete();
				}
			}
		}
	}

	/**
	 * 显示ShortToast
	 */
	public void showCustomToast(String pMsg, int view_position) {
		Crouton.makeText(this, pMsg, Style.CONFIRM, view_position).show();
	}

	public void onClickFeedBack(View v) {
		Intent it = new Intent(this, FeedBackActivity.class);
		startActivity(it);
	}

	public void onClickSetting(View v) {
		Intent it = new Intent(this, SettingActivity.class);
		startActivity(it);
	}

	/**
	 * 获取版本号
	 * 
	 * @param context
	 * @return
	 */
	private int getVersionCode(Context context) {
		int versionCode = 0;
		try {
			// 获取软件版本号
			versionCode = context.getPackageManager().getPackageInfo("com.idconfirmsystem", 1).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this); // 统计时长
		String avatar = ru.mCache.getAsString("avatar");
		String name = ru.mCache.getAsString("name");
		try {
			if (avatar.equals("")) {
				el.loginTextView.setVisibility(View.VISIBLE);
				// el.loginTextView.setText("登录");
			} else {
				ru.isLogin = true;
				el.loginTextView.setVisibility(View.GONE);
				Ion.with(MainActivity.this).load(avatar).asBitmap().setCallback(new FutureCallback<Bitmap>() {

					@Override
					public void onCompleted(Exception e, Bitmap bitmap) {
						// ivHead.setImageBitmap(bitmap);
						el.headRoundedImage.setImageBitmap(bitmap);
					}
				});

			}

			if (!name.equals("")) {
				ru.isLogin = true;
				el.userName.setText(name);
				// el.loginTextView.setText("");
				el.loginTextView.setVisibility(View.GONE);
			} else {
				// el.loginTextView.setText("登录");
				el.loginTextView.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			if (el.mDrawerLayout.isDrawerOpen(el.rl)) {
				el.mDrawerLayout.closeDrawer(el.rl);
				ru.openOrClose = false;
			} else {
				el.mDrawerLayout.openDrawer(el.rl);
				ru.openOrClose = true;
			}
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		el.mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		el.mDrawerToggle.onConfigurationChanged(newConfig);
	}

	private void init() {
		fm = getSupportFragmentManager();
		// 只當容器，主要內容已Fragment呈現
		if (taskFragment == null) {
			taskFragment = new TaskFragment();
		}
		Bundle args = new Bundle();
		args.putString("taskType", "A");
		taskFragment.setArguments(args);
		initFragment(taskFragment);
	}

	// 切換Fragment
	public void changeFragment(Fragment f) {
		changeFragment(f, false);
	}

	// 初始化Fragment(FragmentActivity中呼叫)
	public void initFragment(Fragment f) {
		changeFragment(f, true);
	}

	private void changeFragment(Fragment f, boolean init) {
		FragmentTransaction ft = fm.beginTransaction().setCustomAnimations(R.anim.umeng_fb_slide_in_from_left,
				R.anim.umeng_fb_slide_out_from_left, R.anim.umeng_fb_slide_in_from_right,
				R.anim.umeng_fb_slide_out_from_right);

		ft.replace(R.id.fragment_layout, f);
		if (!init)
			ft.addToBackStack(null);
		ft.commitAllowingStateLoss();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// OffersManager.getInstance(MainActivity.this).onAppExit();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

			if (ru.openOrClose == false) {
				showCustomToast(getString(R.string.back_exit_tips), R.id.fragment_layout);
				return ru.doubleClickExitHelper.onKeyDown(keyCode, event);
			} else {
				el.mDrawerLayout.closeDrawers();
			}

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 创建app本地数据存储空间
	 * 
	 * @author 吴晓明
	 * @throw
	 * @return void
	 */
	public void createSDCardDir() {
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			// 创建一个文件夹对象，赋值为外部存储器的目录
			File sdcardDir = Environment.getExternalStorageDirectory();
			// 得到一个路径，内容是sdcard的文件夹路径和名字
			String path = sdcardDir.getPath() + "/IdConfirmData";
			File path1 = new File(path);
			if (!path1.exists()) {
				// 若不存在，创建目录，可以在应用启动的时候创建
				path1.mkdirs();
				System.out.println("paht ok,ru.path:" + ru.path);
			}
		} else {
			System.out.println("存储设备不可用，创建文件失败");
			return;
		}

	}

	/**
	 * 进行版本更新检测和升级
	 * 
	 * @author 吴晓明
	 * @throw
	 * @return void
	 */
	public void chekedVersionCode() {

		Ion.with(this, Conf.VERSION_CODE).asJsonObject().setCallback(new FutureCallback<JsonObject>() {

			@Override
			public void onCompleted(Exception e, JsonObject result) {
				if (e != null) {
					return;
				}
				String code = result.get("code").getAsString();
				int jsonCode = Integer.parseInt(code);
				// 比较开源中国返回的code跟当前版本code是否一致
				if (jsonCode == ru.versionCode) {
					return;
				} else if (jsonCode > ru.versionCode) {

					CountDownTimer timer = new CountDownTimer(12 * 100, 100) {

						@Override
						public void onTick(long millisUntilFinished) {
							long a = millisUntilFinished / 100;

							if (a == 1) {
								new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)
										.setTitleText("版本检测").setContentText("发现新版本，是否更新？").setCancelText("暂不更新")
										.setConfirmText("马上更新").showCancelButton(true)
										.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
											@Override
											public void onClick(SweetAlertDialog sDialog) {
												sDialog.dismiss();
											}
										}).setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
											@Override
											public void onClick(SweetAlertDialog sDialog) {
												Intent updateIntent = new Intent(MainActivity.this,
														AppUpdateService.class);
												updateIntent.putExtra("titleId", R.string.app_name);
												startService(updateIntent);
												sDialog.dismiss();

											}
										}).show();
							} else {

							}
						}

						@Override
						public void onFinish() {

						}
					};
					timer.start();

				}

			}
		});

	}

	public PendingIntent getDefalutIntent(int flags) {
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(), flags);
		return pendingIntent;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			String result = data.getExtras().getString("result");// 得到新Activity
																	// 关闭后返回的数据
			if (result.equals("exit")) {
				ru.isLogin = false;
				// el.loginTextView.setText("登录");
				el.loginTextView.setVisibility(View.VISIBLE);
				el.userName.setText("vaecer");
				el.headRoundedImage.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		super.onActivityResult(requestCode, resultCode, data);

	}

	/**
	 * 启动动画
	 */
	private void addAnimation() {

		// el.loginTextView.startAnimation(myAnimation_Left);
		el.animLinearLayoutId.startAnimation(ru.myAnimation_Left);

	}

	/**
	 * 动画定义
	 */
	private void myAnimation() {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		displayMetrics = this.getResources().getDisplayMetrics();
		// 获得屏幕宽度
		int screenWidth = displayMetrics.widthPixels;
		ru.myAnimation_Left = new TranslateAnimation(-screenWidth, 0, 0, 0);
		ru.myAnimation_Left.setDuration(1800);
	}

	/**
	 * 选中的菜单中各种任务切换
	 * 
	 * @param position
	 *            选中菜单的第几个菜单条
	 * @author 吴晓明
	 * @throw
	 * @return void
	 */
	private void switchTask(int position) {
		UserMenu cMenu = new UserMenu();
		cMenu.setMenuId(position + "");
		cMenu.setMenuName(ru.menus[position]);
		AppConfig.curMenu = cMenu;

		if (ru.menus[position].contains("早")) {
			goTaskFragment("A");
		} else if (ru.menus[position].contains("中")) {
			goTaskFragment("C");
		} else if (ru.menus[position].contains("晚")) {
			goTaskFragment("B");
		} else if (ru.menus[position].equals(MenuName.system_notice)) {
			initFragment(new SendMsgFragment());
		}else if (ru.menus[position].equals(MenuName.system_notice_read)) {
			/*Intent it = new Intent(MainActivity.this, NoticeActivity.class);
			startActivity(it);*/
			initFragment(new RecevieMsgFragment());
		} else if (ru.menus[position].equals(MenuName.bag_verify_list)) {
			/*Intent it = new Intent(MainActivity.this, BagVerifyQueryActivity.class);
			startActivity(it);*/
			
			initFragment(new BagVerifyFragment());
		} else if (ru.menus[position].equals(MenuName.bag_task_list)) {
			initFragment(new BagVerifyQueryListFragment());
		} else {
			Toast.makeText(getApplicationContext(), ru.menus[position] + "正在开发", Toast.LENGTH_SHORT).show();
		}
	
	}

	public void goTaskFragment(String taskType) {
		Bundle bundle = new Bundle();
		bundle.putString("taskType", taskType);

		taskFragment = null;
		taskFragment = new TaskFragment();
		taskFragment.setArguments(bundle);

		FragmentTransaction ft = fm.beginTransaction().setCustomAnimations(R.anim.umeng_fb_slide_in_from_left,
				R.anim.umeng_fb_slide_out_from_left, R.anim.umeng_fb_slide_in_from_right,
				R.anim.umeng_fb_slide_out_from_right);
		ft.attach(taskFragment);

//		taskFragment.loadTask(taskType);
		initFragment(taskFragment);

	}


	@Override
	public void setRootView() {
		// TODO Auto-generated method stub

	}

}
